package org.example.Page;

import org.example.POJO.game.Room;
import org.example.POJO.online.MyMessage;
import org.example.POJO.online.Record;
import org.example.POJO.online.User;
import org.example.Utils.SocketUtil;
import org.example.Utils.UserFileManager;
import org.example.sever.ClientThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.border.EmptyBorder;

public class GameLobby extends JFrame {
    private Socket socket;

    private String username;

    private User user = new User(username, "", "", null);
    private Vector<String> clientList;//所有在线人数

    private JList Jlist;

    private DefaultListModel model;

    private ClientThread ct;

    private UserFileManager userFileManager = new UserFileManager();

    private Vector<Room> rooms = new Vector<>();

    private JPanel RoomPanels ;

    private JPanel containerTwo;


    public GameLobby setUsername(String username) {
        this.username = username;
        return this;
    }


    private static JLabel createScaledAvatar(String imagePath, int width, int height) {
        ImageIcon avatarIcon = new ImageIcon(imagePath); // 加载图片
        Image avatarImg = avatarIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH); // 缩放到指定大小
        return new JLabel(new ImageIcon(avatarImg));
    }

    public GameLobby(Socket socket, String username) throws IOException {

        this.socket = socket;
        this.username = username;

        setTitle("游戏大厅");
        setSize(800, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        model = new DefaultListModel();

        Jlist = new JList(model);

        // 设置主背景为灰色
        getContentPane().setBackground(Color.lightGray);

        // 创建主面板，使用GridBagLayout布局管理器
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        // 左侧容器
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 0.85; // 占70%宽度
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;

        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
        leftPanel.setBackground(new Color(255, 250, 250)); // 设置雪白色背景

        // 容器一
        JPanel containerOne = new JPanel();
        containerOne.setLayout(new BorderLayout()); // 设置布局管理器为 BorderLayout
        containerOne.setBorder(BorderFactory.createLineBorder(Color.RED, 2));
        containerOne.setBackground(new Color(255, 250, 250)); // 设置雪白色背景

        // 创建按钮
        JButton joinButton = new JButton("开始游戏");
        JButton exitButton = new JButton("退出");

        // 创建一个面板来放置按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(joinButton);
        buttonPanel.add(exitButton);

        // 将按钮面板添加到 containerOne 的右侧
        containerOne.add(new JLabel("<<游戏大厅>>"), BorderLayout.CENTER);
        containerOne.add(buttonPanel, BorderLayout.EAST);

        containerTwo = new JPanel();
        containerTwo.setBackground(new Color(81, 114, 158)); // 背景颜色

        for (int i = 0; i < 15; i++) {
            Room room = new Room("room" + (i + 1)); // 唯一 roomId
            rooms.add(room); // 添加到房间列表
        }

        RoomPanels = createRoomPanels(rooms, user, socket, userFileManager, username);
        // 设置 matchPanel 的首选、最小和最大尺寸以确保固定宽度和高度
        Dimension fixedSize = new Dimension(600, 500); // 宽度为 600 像素，高度为 400 像素
        RoomPanels.setPreferredSize(fixedSize);
        containerTwo.add(RoomPanels);
        containerTwo.setVisible(true);


        // 将容器一和容器二添加到左侧容器
        leftPanel.add(containerOne, BorderLayout.NORTH);
        leftPanel.add(containerTwo, BorderLayout.CENTER);

        mainPanel.add(leftPanel, gbc);

        // 右侧容器
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 0.15; // 占30%宽度
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHEAST;

        JPanel rightPanel = new JPanel(new GridLayout(2, 1)); // 使用GridLayout来平分高度
        rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
        rightPanel.setBackground(new Color(255, 250, 250)); // 设置雪白色背景

        // 容器三
        JPanel containerThree = new JPanel(new BorderLayout()); // 使用BorderLayout来管理组件位置
        containerThree.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
        containerThree.setBackground(new Color(255, 250, 250)); // 设置雪白色背景

        // 加载图片
        String imagePath = "picture/img/boy1.gif";
        ImageIcon imageIcon = new ImageIcon(imagePath);

        // 创建一个 JLabel 来显示图片
        JLabel imageLabel = new JLabel(imageIcon);

        // 展示头像
        String avatar = userFileManager.getAvatar(username);
        if (avatar.equals("null")||avatar == null) {
            avatar = "picture/face/1-1.gif";
        }
        ImageIcon avatarIcon1 = new ImageIcon(avatar);
        JLabel imageLabel1 = new JLabel(avatarIcon1);
        JLabel nicknameLabel = new JLabel(username);

        // 创建一个面板来容纳头像和用户名，并设置其布局为垂直 BoxLayout
        JPanel avatarNamePanel = new JPanel();
        avatarNamePanel.setLayout(new BoxLayout(avatarNamePanel, BoxLayout.Y_AXIS));
        avatarNamePanel.add(imageLabel1);
        avatarNamePanel.add(nicknameLabel);

        // 将包含头像和用户名的面板添加到容器三的底部
        JPanel centeredPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); // 使用 FlowLayout 居中对齐
        centeredPanel.setBackground(new Color(255, 250, 250)); // 保持背景颜色一致
        centeredPanel.add(avatarNamePanel);

        // 将包含头像和用户名的居中面板添加到容器三的底部
        containerThree.add(imageLabel, BorderLayout.CENTER);
        containerThree.add(centeredPanel, BorderLayout.SOUTH); // 添加到底部
        // 将容器三添加到右侧容器
        rightPanel.add(containerThree);

        // 在构造函数内，创建 JList 并设置其模型
        Jlist = new JList<>(model);
        Jlist.addMouseListener(new MouseAdapter() {

            @Override
            //鼠标点击事件
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    System.out.println("双击" + Jlist.getSelectedIndex());
                    String to = clientList.elementAt(Jlist.getSelectedIndex());
                    //弹出提示框
                    int result = JOptionPane.showConfirmDialog(null, "确定要挑战" + to + "吗？", "提示", JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        System.out.println("确定");
                        MyMessage req = new MyMessage();
                        req.setType(MyMessage.Type.FIGHT);
                        System.out.println("游戏大厅：：：：发送挑战");
                        req.setFrom(username);
                        req.setTo(to);
                        try {
                            SocketUtil.send(socket, req);
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    } else {
                        System.out.println("取消");
                    }
                }
            }
        });
        JScrollPane scrollPane = new JScrollPane(Jlist);

        // 容器四
        JPanel containerFour = new JPanel(new BorderLayout());
        containerFour.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
        containerFour.setBackground(new Color(255, 250, 250)); // 设置雪白色背景

        JLabel titleLabel = new JLabel("游戏在线");
        titleLabel.setHorizontalAlignment(SwingConstants.LEFT); // 左对齐
        titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 0)); // 设置内边距，让标题更美观

        // 添加标题到顶部
        containerFour.add(titleLabel, BorderLayout.NORTH);
        // 将包含 JList 的 JScrollPane 添加到中心位置
        containerFour.add(scrollPane, BorderLayout.CENTER);

        // 将容器三和容器四添加到右侧容器
        rightPanel.add(containerThree);
        rightPanel.add(containerFour);

        mainPanel.add(rightPanel, gbc);

        add(mainPanel);
        setVisible(true);

        try {
            getClientList();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public static JPanel createRoomPanels(Vector<Room> rooms, User user, Socket socket, UserFileManager userFileManager, String username) {
        // 主容器面板，用于容纳所有单独的房间面板，按5行3列布局
        JPanel containerPanel = new JPanel();
        containerPanel.setLayout(new GridLayout(5, 3, 10, 10)); // 设置为 5 行 3 列布局，每个组件之间间距10像素

        // 只处理前15个房间
        int roomCount = Math.min(rooms.size(), 15);

        for (int i = 0; i < roomCount; i++) {
            Room room = rooms.get(i);

            // 创建一个新的容器来包含三个组件
            JPanel roomComponentsContainer = new JPanel();
            roomComponentsContainer.setLayout(new GridLayout(1, 3)); // 水平排列三个组件
            roomComponentsContainer.setBackground(new Color(81, 114, 158)); // 继承父面板背景颜色
            roomComponentsContainer.setBorder(new EmptyBorder(15, 15, 15, 15)); // 四边外边距为 15 像素

            // 创建左侧用户头像
            JLabel leftAvatar = createScaledAvatar(room.getLeftAvatar(), 45, 45);
            leftAvatar.setBackground(new Color(240, 240, 240)); // 浅灰背景
            leftAvatar.setOpaque(true); // 使背景颜色生效

            // 创建中间棋盘样例
            JLabel chessboard = createScaledAvatar("picture/img/xqnoone.gif", 45, 45);
            chessboard.setBackground(new Color(200, 200, 200)); // 棋盘背景
            chessboard.setOpaque(true); // 使背景颜色生效

            // 创建右侧用户头像
            JLabel rightAvatar = createScaledAvatar(room.getRightAvatar(), 45, 45);
            rightAvatar.setBackground(new Color(240, 240, 240)); // 浅灰背景
            rightAvatar.setOpaque(true); // 使背景颜色生效
            rightAvatar.setFocusable(true);

            // 定义进入房间的公共逻辑
            MouseAdapter enterRoomListener = new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (user.getRoomId() != null) {
                        JOptionPane.showMessageDialog(null, "您已加入房间" + user.getRoomId(), "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    try {
                        int result = JOptionPane.showConfirmDialog(null, "是否进入房间" + room.getRoomId(), "提示", JOptionPane.YES_NO_OPTION);
                        if (result == JOptionPane.YES_OPTION) {
                            user.setRoomId(room.getRoomId());
                            String avatar = userFileManager.getAvatar(username);
                            leftAvatar.setIcon(new ImageIcon(avatar));

                            MyMessage request = new MyMessage();
                            request.setType(MyMessage.Type.JOIN);
                            request.setFrom(username);
                            request.setContent(room.getRoomId().toString());

                            try {
                                SocketUtil.send(socket, request);
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    } catch (Exception ex) {
                        System.out.println(ex.getMessage());
                    }
                }
            };

            // 添加鼠标事件到左侧和右侧用户头像
            leftAvatar.addMouseListener(enterRoomListener);
            rightAvatar.addMouseListener(enterRoomListener);

            // 将三个组件添加到roomComponentsContainer中
            roomComponentsContainer.add(leftAvatar);
            roomComponentsContainer.add(chessboard);
            roomComponentsContainer.add(rightAvatar);

            // 将roomComponentsContainer添加到容器面板中
            containerPanel.add(roomComponentsContainer);
        }

        // 如果房间数量不足15个，填充空白面板以保持网格完整
        for (int i = roomCount; i < 15; i++) {
            containerPanel.add(new JPanel()); // 空白面板
        }

        return containerPanel;
    }


    public void getClientList() throws IOException {
        MyMessage req = new MyMessage();
        req.setType(MyMessage.Type.LIST);
        req.setFrom(username);
        SocketUtil.send(socket, req);
        ct = new ClientThread(socket, new ClientThread.ResponseListener() {
            @Override
            public void Success(MyMessage response) {
                System.out.println("gameLobby--------->" + response);
                switch (response.getType()) {
                    case SUCCESS:
                        if (response.getContent() instanceof Vector) {
                            model.clear();
                            clientList = (Vector<String>) response.getContent();
                            clientList.forEach(item -> {
                                model.addElement(item);
                            });
                            Jlist.validate();
                        }
                        break;
                    case FIGHT:
                        System.out.println("接受挑战请求");
                        int result = JOptionPane.showConfirmDialog(null, "是否接受挑战？", "对方发起的挑战", JOptionPane.YES_NO_OPTION);
                        MyMessage request = new MyMessage();
                        request.setFrom(username);
                        request.setTo(response.getFrom());
                        request.setContent(new Record());
                        if (result == JOptionPane.YES_OPTION) {
                            //同意
                            request.setType(MyMessage.Type.FIGHT_SUCCESS);
                        } else {
                            //拒绝
                            request.setType(MyMessage.Type.FIGHT_DEFEAT);
                        }
                        try {
                            SocketUtil.send(socket, request);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case FIGHT_SUCCESS:
                        MyFrame myFrame = null;
                        if (username.equals(response.getTo())) {
                            myFrame = new MyFrame(socket, username, response.getFrom());
                        } else {
                            myFrame = new MyFrame(socket, username, response.getTo()); // 打开游戏界面
                        }

                        myFrame.setUsername(username);
                        // 划分阵营，默认发起者为红
                        if (username.equals(response.getFrom())) {
                            myFrame.setCamp(response.getFromCamp());
                            myFrame.setLocked(false);
                            myFrame.setUsername(response.getFrom());
                            myFrame.setTo(response.getTo());
                        } else {
                            myFrame.setCamp(response.getToCamp());
                            myFrame.setLocked(true); // 黑方锁定棋盘
                            myFrame.setUsername(response.getTo());
                            myFrame.setTo(response.getFrom());
                        }
                        ct.setShutdown(true); // 关掉当前线程
                        GameLobby.this.dispose();
                        break;
                    case FIGHT_DEFEAT:
                        System.out.println("拒绝挑战");
                        JOptionPane.showMessageDialog(null, "对方拒绝挑战");
                        break;
                    case JOIN:
                        if (response.getContent() instanceof Vector) {
                            rooms.clear();
                            rooms = (Vector<Room>) response.getContent();
                            System.out.println("房间列表：" + rooms);
                            //重新画
                            RoomPanels = createRoomPanels(rooms, user, socket, userFileManager, username);
                            containerTwo.removeAll();
                            containerTwo.add(RoomPanels);
                            containerTwo.validate();
                            containerTwo.repaint();
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        ct.start();
    }

}